#include "invalidhighlighter.h"
#include <QRegExp>
#include <QDebug>

InvalidHighlighter::InvalidHighlighter(QString InvalidStr,QString validStr,QTextDocument* parent):QSyntaxHighlighter(parent)
{
    this->m_invalidPattern=QRegExp(InvalidStr);
    this->m_invalidFormat.setForeground(Qt::red);
    this->m_validPattern=QRegExp(validStr);
    this->m_validFormat.setForeground(Qt::green);
}


void InvalidHighlighter::setValidPattern(QString str)
{
    this->m_validPattern=QRegExp(str);
    qDebug()<<"InvalidHighlighter::setValidPattern:new pattern set";
}
void InvalidHighlighter::setInvalidPattern(QString str)
{
    this->m_invalidPattern=QRegExp(str);
    qDebug()<<"InvalidHighlighter::setInvalidPattern:new pattern set";
}

void InvalidHighlighter::highlightBlock(const QString &text)
{
    //QTextCharFormat myClassFormat;
    //myClassFormat.setFontWeight(QFont::Bold);
    //myClassFormat.setForeground(Qt::darkRed);
    int length;
    int indexV = text.indexOf(this->m_validPattern);
    int indexIV = text.indexOf(this->m_invalidPattern);
    //qDebug()<<"indexV"<<indexV<<"indexIV"<<indexIV;

    while (indexV >= 0 || indexIV >=0)
    {
        //qDebug()<<"indexV"<<indexV<<"indexIV"<<indexIV;
        if (indexV >=0 && indexIV>=0)
        {
            if ( indexV < indexIV)
            {
                length = this->m_validPattern.matchedLength();
                setFormat(indexV, length, this->m_validFormat);
                indexV = indexV+length;
                indexIV = indexV;
            }
            else if (indexIV < indexV)
            {
                length = this->m_invalidPattern.matchedLength();
                setFormat(indexIV, length, this->m_invalidFormat);
                indexIV = indexIV + length;
                indexV = indexIV;
            }
            else if (indexIV == indexV)
            {
                qDebug()<<"SAME SYNTAX! CASTROPHICAL ERROR";
                indexV +=10000;
                indexIV +=10000;
            }
        }
        else if (indexV >=0)
        {
            length = this->m_validPattern.matchedLength();
            setFormat(indexV, length, this->m_validFormat);
            indexV = indexV+length;
            indexIV = indexV;
        }
        else if (indexIV >=0 )
        {
            length = this->m_invalidPattern.matchedLength();
            setFormat(indexIV, length, this->m_invalidFormat);
            indexIV = indexIV+length;
            indexV = indexIV;
        }
        indexIV = text.indexOf(this->m_invalidPattern, indexIV );
        indexV = text.indexOf(this->m_validPattern, indexV);
    }
}

